import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/widgets/BGExamImageWidget.dart';

import 'BGExamWidget.dart';
import 'BGSinglePlayer.dart';

class BGExamTypeMatch extends StatelessWidget {
  final QuestionItem item;
  final BGExamWidgetMode mode;
  final Function getAnswer;

  const BGExamTypeMatch(
      {Key? key,
      required this.item,
      required this.mode,
      required this.getAnswer})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    bool isGrade =
        (mode == BGExamWidgetMode.Grade || mode == BGExamWidgetMode.Graded);
    bool isEditable =
        (mode == BGExamWidgetMode.Practice || mode == BGExamWidgetMode.Test);
    List<Widget> options = [];
    var itemWidth = (MediaQuery.of(context).size.width - 150) * 0.4;
    if (isGrade) {
      itemWidth = (MediaQuery.of(context).size.width - 150) * 0.3;
    }
    bool isHaveImage = false;
    if (item.body != null && item.body!.length > 1) {
      List<QuestionContent> leftList = <QuestionContent>[];
      RxList<QuestionContent> rightList = <QuestionContent>[].obs;
      leftList = item.body!.first;
      rightList.value = item.body![1];
      if (isEditable) _matchAnswer(leftList, rightList);
      for (int i = 0; i < leftList.length; i++) {
        String? show = leftList[i].show ?? "";
        if (show == "image") {
          isHaveImage = true;
        }
      }
      var matchKey = GlobalKey();
      for (int i = 0; i < rightList.length; i++) {
        rightList[i].pdf = matchKey.toString();
        String? show = rightList[i].show ?? "";
        if (show == "image") {
          isHaveImage = true;
        }
      }
      options.add(Container(
        width: itemWidth,
        child: ListView.builder(
          physics: NeverScrollableScrollPhysics(),
          itemCount: leftList.length,
          shrinkWrap: true,
          itemBuilder: (context, index) {
            return _buildMatchItem(
                leftList[index], isHaveImage, false, itemWidth, context);
          },
        ),
      ));
      if (isEditable) {
        options.add(Container(
          width: itemWidth,
          child: Obx(() {
            return ListView.builder(
              physics: NeverScrollableScrollPhysics(),
              itemCount: rightList.length,
              shrinkWrap: true,
              itemBuilder: (context, index) {
                return DragTarget<QuestionContent>(
                  builder: (BuildContext context, List<dynamic> accepted,
                      List<dynamic> rejected) {
                    return Container(
                      child: Draggable<QuestionContent>(
                        onDragCompleted: () {
                          _matchAnswer(leftList, rightList);
                        },
                        data: rightList[index],
                        child: _buildMatchItem(rightList[index], isHaveImage,
                            false, itemWidth, context),
                        feedback: _buildMatchItem(rightList[index], isHaveImage,
                            true, itemWidth, context),
                        childWhenDragging: isHaveImage
                            ? SizedBox(width: itemWidth, height: 160)
                            : SizedBox(width: itemWidth, height: 84),
                      ),
                    );
                  },
                  onWillAccept: (QuestionContent? body) {
                    return true;
                  },
                  onAccept: (QuestionContent body) {
                    if (body.pdf == rightList[0].pdf) {
                      for (int i = 0; i < rightList.length; i++) {
                        QuestionContent aBody = rightList[i];
                        if (body.baseValue == aBody.baseValue) {
                          rightList.replaceRange(i, i + 1, [rightList[index]]);
                        }
                      }
                      rightList.replaceRange(index, index + 1, [body]);
                    }
                  }
                );
              },
            );
          }),
        ));
      } else {
        List solutionList = [];
        if (item.solution != null && item.solution!.isNotEmpty) {
          for (int i = 0; i < leftList.length; i++) {
            QuestionContent leftItem = leftList[i];
            for (int j = 0; j < item.solution!.length; j++) {
              String answerStr = item.solution![j];
              List tempList = answerStr.split('|');
              if (leftItem.baseValue != null &&
                  (tempList.first == leftItem.baseValue! ||
                      tempList.last == leftItem.baseValue!)) {
                for (int k = 0; k < rightList.length; k++) {
                  QuestionContent rightItem = rightList[k];
                  if (rightItem.baseValue != null &&
                      (tempList.last == rightItem.baseValue! ||
                          tempList.first == rightItem.baseValue!)) {
                    solutionList.add(rightItem);
                  }
                }
              }
            }
          }
        }
        if (isGrade) {
          List answerList = [];
          List<bool> judge = [];
          if (item.answer != null && item.answer!.isNotEmpty) {
            for (int i = 0; i < leftList.length; i++) {
              QuestionContent leftItem = leftList[i];
              bool isHave = false;
              for (int j = 0; j < item.answer!.length; j++) {
                String answerStr = item.answer![j];
                List tempList = answerStr.split('|');
                if (leftItem.baseValue != null &&
                    (tempList.first == leftItem.baseValue! ||
                        tempList.last == leftItem.baseValue!)) {
                  for (int k = 0; k < rightList.length; k++) {
                    QuestionContent rightItem = rightList[k];
                    if (rightItem.baseValue != null &&
                        (tempList.last == rightItem.baseValue! ||
                            tempList.first == rightItem.baseValue!)) {
                      isHave = true;
                      answerList.add(rightItem);
                    }
                  }
                }
              }
              if (!isHave) {
                answerList.add(QuestionContent());
              }
            }
          }
          if (solutionList.isNotEmpty &&
              answerList.isNotEmpty &&
              solutionList.length == answerList.length) {
            for (int i = 0; i < solutionList.length; i++) {
              if (answerList[i].baseValue != null &&
                  solutionList[i].baseValue != null &&
                  solutionList[i].baseValue == answerList[i].baseValue) {
                judge.add(true);
              } else {
                judge.add(false);
              }
            }
          }
          options.add(
            Row(children: [
              SizedBox(
                  width: 30,
                  child: ListView.builder(
                      itemCount: judge.length,
                      physics: NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (context, index) {
                        return Container(
                            height: isHaveImage ? 160 : 84,
                            child: Icon(
                                judge[index] ? Icons.check : Icons.close,
                                color: judge[index]
                                    ? Color(0xFF409DAB)
                                    : Colors.red,
                                size: 26));
                      })),
              SizedBox(width: 10),
              Container(
                width: itemWidth,
                child: ListView.builder(
                  physics: NeverScrollableScrollPhysics(),
                  itemCount: answerList.length,
                  shrinkWrap: true,
                  itemBuilder: (context, index) {
                    return _buildMatchItem(answerList[index], isHaveImage,
                        false, itemWidth, context);
                  },
                ),
              )
            ]),
          );
          options.add(Container(
            width: itemWidth,
            child: ListView.builder(
              physics: NeverScrollableScrollPhysics(),
              itemCount: solutionList.length,
              shrinkWrap: true,
              itemBuilder: (context, index) {
                return _buildMatchItem(solutionList[index], isHaveImage, false,
                    itemWidth, context);
              },
            ),
          ));
        } else if (mode == BGExamWidgetMode.Review) {
          options.add(Container(
            width: itemWidth,
            child: ListView.builder(
              physics: NeverScrollableScrollPhysics(),
              itemCount: solutionList.length,
              shrinkWrap: true,
              itemBuilder: (context, index) {
                return _buildMatchItem(solutionList[index], isHaveImage, false,
                    itemWidth, context);
              },
            ),
          ));
        }
      }
    }
    return Container(
      child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceAround, children: options),
    );
  }

  _matchAnswer(List leftList, List rightList) {
    List<String> answer = [];
    for (int i = 0; i < leftList.length; i++) {
      QuestionContent leftBody = leftList[i];
      QuestionContent rightBody = rightList[i];
      String answerStr = leftBody.baseValue! + '|' + rightBody.baseValue!;
      answer.add(answerStr);
    }
    getAnswer(answer);
  }

  Widget _buildMatchItem(QuestionContent body, bool isHaveImage,
      bool isFeedback, double itemWidth, BuildContext context) {
    Widget option = SizedBox();
    String? show = body.show;
    if (show != null) {
      if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_TEXT)) {
        option = Card(
            color: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
              side: BorderSide(
                  color: isFeedback ? Color(0xffff0000) : Color(0xff5B9BD5),
                  width: 2),
            ),
            child: Container(
               padding: EdgeInsets.only(left: 6,right: 6),
                alignment: Alignment.center,
                child: Text(body.text ?? '', style: TextStyle(fontSize: 16))));
      }
      if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_AUDIO)) {
        option = Container(
            width: itemWidth,
            decoration: BoxDecoration(
                border: Border.all(
                    color: isFeedback ? Color(0xffff0000) : Color(0xff5B9BD5),
                    width: 2),
                color: Colors.white,
                borderRadius: BorderRadius.circular(12)),
            child: IconButton(
              iconSize: 48,
              icon: const Icon(
                Icons.play_circle,
                color: Colors.blue,
              ),
              onPressed: () {
                BGSinglePlayer().play(body.audio);
              },
            ));
      }
      if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_IMAGE)) {
        option = BGExamImageWidget(imgUrl: body.image, source: 'MatchItem');
      }
    }
    return Container(
        alignment: Alignment.center,
        width: itemWidth,
        height: isHaveImage ? 160 : 84,
        padding: const EdgeInsets.all(6.0),
        child: option);
  }
}
